import React, { ChangeEvent } from 'react';

interface BugFormProps {
  formData: {
    remarks: string;
    apiAddress: string;
    requestMethod: string;
    requestHeaders: string;
    requestBody: string;
    errorMessage: string;
  };
  setFormData: (data: BugFormProps['formData']) => void;
}

const BugForm: React.FC<BugFormProps> = ({ formData, setFormData }) => {
  const handleTextChange = (field: keyof BugFormProps['formData']) => (e: ChangeEvent<HTMLTextAreaElement | HTMLInputElement | HTMLSelectElement>) => {
    setFormData({ ...formData, [field]: e.target.value });
  };

  const handlePaste = async (e: React.ClipboardEvent<HTMLTextAreaElement>) => {
    const items = e.clipboardData.items;
    let hasImagePasted = false;

    for (const item of items) {
      if (item.type.startsWith('image/')) {
        e.preventDefault();
        hasImagePasted = true;
        const blob = item.getAsFile();
        if (blob) {
          try {
            // 将图片转换为 Base64
            const reader = new FileReader();
            reader.onload = () => {
              const base64String = reader.result as string;
              // 在当前文本后追加图片的 markdown 格式
              const currentText = formData.errorMessage;
              const newText = currentText + (currentText ? '\n' : '') + `![异常截图](${base64String})`;
              setFormData({ ...formData, errorMessage: newText });
            };
            reader.readAsDataURL(blob);
          } catch (error) {
            console.error('处理图片失败:', error);
            alert('处理图片失败，请重试');
          }
        }
        break;
      }
    }

    // 如果不是图片，让浏览器处理默认的粘贴行为
    if (!hasImagePasted) {
      return;
    }
  };

  const clearFields = () => {
    setFormData({
      remarks: '',
      apiAddress: '',
      requestMethod: '',
      requestHeaders: '',
      requestBody: '',
      errorMessage: ''
    });
  };

  const handleClearMethod = () => {
    setFormData({ ...formData, requestMethod: '' });
  };

  return (
    <div className='flex-[2] min-w-[400px]'>
      <div className='flex justify-between items-center mb-4'>
        <h1 className='text-blue-500 text-2xl font-bold'>错误信息生成器</h1>
        <button
          className='p-2 text-red-500 hover:text-red-600 hover:bg-gray-100 rounded-full transition-colors'
          onClick={clearFields}
          title='一键清空'
        >
          <svg
            xmlns='http://www.w3.org/2000/svg'
            className='h-6 w-6'
            fill='none'
            viewBox='0 0 24 24'
            stroke='currentColor'
          >
            <path
              strokeLinecap='round'
              strokeLinejoin='round'
              strokeWidth={2}
              d='M19 7l-.867 12.142A2 2 0 0116.138 21H7.862a2 2 0 01-1.995-1.858L5 7m5 4v6m4-6v6m1-10V4a1 1 0 00-1-1h-4a1 1 0 00-1 1v3M4 7h16'
            />
          </svg>
        </button>
      </div>
      <textarea
        className='w-full p-2 mb-4 border border-gray-300 rounded h-20'
        value={formData.remarks}
        onChange={handleTextChange('remarks')}
        placeholder='备注信息'
      ></textarea>
      <input
        type='text'
        className='w-full p-2 mb-4 border border-gray-300 rounded'
        value={formData.apiAddress}
        onChange={handleTextChange('apiAddress')}
        placeholder='API 地址'
      />
      <div className='relative mb-4'>
        <select
          className='w-full p-2 border border-gray-300 rounded appearance-none bg-white pr-16'
          value={formData.requestMethod}
          onChange={handleTextChange('requestMethod')}
        >
          <option value=''>请选择请求方式</option>
          <option value='GET'>GET</option>
          <option value='POST'>POST</option>
          <option value='PUT'>PUT</option>
          <option value='DELETE'>DELETE</option>
        </select>
        {formData.requestMethod && (
          <button
            className='absolute right-7 top-1/2 -translate-y-1/2 p-1 text-gray-400 hover:text-gray-600'
            onClick={handleClearMethod}
            title='清空'
          >
            <svg
              xmlns='http://www.w3.org/2000/svg'
              className='h-4 w-4'
              fill='none'
              viewBox='0 0 24 24'
              stroke='currentColor'
            >
              <path
                strokeLinecap='round'
                strokeLinejoin='round'
                strokeWidth={2}
                d='M6 18L18 6M6 6l12 12'
              />
            </svg>
          </button>
        )}
        <div className='absolute right-2 top-1/2 -translate-y-1/2 pointer-events-none text-gray-500'>
          <svg
            xmlns='http://www.w3.org/2000/svg'
            className='h-4 w-4'
            fill='none'
            viewBox='0 0 24 24'
            stroke='currentColor'
          >
            <path
              strokeLinecap='round'
              strokeLinejoin='round'
              strokeWidth={2}
              d='M19 9l-7 7-7-7'
            />
          </svg>
        </div>
      </div>
      <textarea
        className='w-full p-2 mb-4 border border-gray-300 rounded h-20'
        value={formData.requestHeaders}
        onChange={handleTextChange('requestHeaders')}
        placeholder='headers'
      ></textarea>
      <textarea
        className='w-full p-2 mb-4 border border-gray-300 rounded h-20'
        value={formData.requestBody}
        onChange={handleTextChange('requestBody')}
        placeholder='入参'
      ></textarea>
      <div className='relative'>
        <textarea
          className='w-full p-2 mb-4 border border-gray-300 rounded h-20'
          value={formData.errorMessage}
          onChange={handleTextChange('errorMessage')}
          onPaste={handlePaste}
          placeholder='异常信息（支持粘贴图片）'
        ></textarea>
        <div className='absolute right-2 bottom-6 text-gray-400 text-sm'>支持粘贴图片</div>
      </div>
    </div>
  );
};

export default BugForm;
